package com.lazyshopkeeper.front.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.lazyshopkeeper.front.apiService.IUserService;
import com.lazyshopkeeper.front.apiService.IVasService;
import com.lazyshopkeeper.front.common.Constant;
import com.taobao.api.ApiException;
import com.taobao.api.domain.ArticleUserSubscribe;
import com.taobao.api.domain.User;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	@Autowired
	private IUserService userService;
	@Autowired
	private com.lazyshopkeeper.front.service.IUserService localUserService;
	@Autowired
	private IVasService vasService;
	
	/**
	 * Simply selects the home view to render by returning its name.
	 * @throws ApiException 
	 */
	@RequestMapping(value = "", method = RequestMethod.GET)
	public String home(Model model, HttpSession session) throws ApiException {
		String sessionKey = (String)session.getAttribute(Constant.SESSION_KEY);
		User user = localUserService.getUser((String)session.getAttribute(Constant.NICK));
		if(user == null){
			user = userService.getCurrentUser(sessionKey);
			localUserService.saveNewUser(user);
		}
		List<ArticleUserSubscribe> ausList = vasService.getUserVasInfo(user.getNick(), Constant.ARTICLE_CODE);
		if(ausList == null){
			model.addAttribute(Constant.USER_LEVEL, "免费版");
		} else {
			model.addAttribute(Constant.USER_LEVEL, Constant.vasMapper.get(ausList.get(0).getItemCode()));
		}
		return "home";
	}
	
	@ExceptionHandler(Exception.class)
	@ResponseStatus(value=HttpStatus.METHOD_FAILURE, reason="Method Failure")
	public String exceptions(Exception ex, HttpServletRequest request){
		request.setAttribute("error", ex.getMessage());
		return "err/index";
	}
}
